
<template>
  <div class="debug">
    <el-row>
      <el-col :span="4">
        <el-input placeholder="请输入内容" v-model="baseUrl" readonly size="small ">
          <template slot="prepend">{{ info.method }}</template>
        </el-input>
      </el-col>
      <el-col :span="16">
        <el-input placeholder="请输入内容" v-model="info.path" disabled class="path" size="small"></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" icon="el-icon-s-promotion" size="small" @click="submit">biu biu~</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="first">
            <template slot="title">HEADERS</template>
            <el-row>
              <el-col :span="4">
                <el-input placeholder v-model="header.name" disabled size="small"></el-input>
              </el-col>
              <el-col :span="1">
                <div class="v-spn-1">=</div>
              </el-col>
              <el-col :span="19">
                <el-input placeholder="请输入内容" v-model="header.value" size="small"></el-input>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item :title="getMethod" v-if="IsShow" name="sencod">
            <el-row v-for="(query, index) in querys" :key="index">
              <el-col :span="4">
                <el-input placeholder v-model="query.name" disabled size="small"></el-input>
              </el-col>
              <el-col :span="1">
                <div class="v-spn-1">
                  <el-checkbox v-model="query.isChecked" size="medium "></el-checkbox>
                  <span style="padding-left:5px">=</span>
                </div>
              </el-col>
              <el-col :span="18">
                <el-input placeholder="请输入内容" v-model="query.value" size="small"></el-input>
              </el-col>
            </el-row>
          </el-collapse-item>

          <el-collapse-item :title="getMethod" v-else name="three">
            <el-row v-for="(body, index) in bodys" :key="index">
              <el-col :span="4">
                <el-input placeholder v-model="body.name" disabled size="small"></el-input>
              </el-col>
              <el-col :span="1">
                <div class="v-spn-1">
                  <el-checkbox v-model="body.isChecked" size="medium "></el-checkbox>
                  <span style="padding-left:5px">=</span>
                </div>
              </el-col>
              <el-col :span="5" @click="handleJsonView(body)">
                <json-viewer :value="body.model" :expand-depth="3" copyable boxed sort></json-viewer>
              </el-col>
              <el-col :span="13">
                <!-- <div class="ace-editor" ref="ace"></div> -->
                <el-input
                  type="textarea"
                  :rows="5"
                  placeholder="请输入内容"
                  style="margin-left: 10px;"
                  v-model="body.value"
                ></el-input>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-col>
    </el-row>

    <h3>Response</h3>
    <div>
      <json-viewer :value="response" :expand-depth="4" copyable boxed sort></json-viewer>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  props: {
    id: {
      type: String,
      default: 0
    }
  },
  data() {
    return {
      activeNames: "first",
      info: {},
      header: {},
      querys: [],
      bodys: [],
      response: ""
    };
  },
  mounted() {
  //  let container = this.$refs.ace;
  //  let options = {
  //         mode: 'text',
  //         indentation: 2,
  //         search: true
  //       }
  //  let editor = new this.$jsoneditor(container, options)

  },
  created() {
    this.info = this.$store.state.permission.paths.find(el => {
      return el.id == this.id;
    });
    this.header = this.info.data.parameters.find(el => {
      return el.in == "header" && el.name == "Authorization";
    });
    this.$set(this.header, "value", "");
    this.ChooseMethod(this.info.method);
    console.log(this.header);
  },
  methods: {
    submit() {
      if (this.IsShow) {
        this.getHttp();
      } else {
        this.postHttp();
      }
    },
    getParams(cquerys) {
      var reQ = {};
      cquerys.forEach(el => {
        reQ[el.name] = el.value;
      });
      return reQ;
    },
    postParams(cbodys) {
      if (!cbodys || cbodys.length == 0) return null;
      if (cbodys.length == 1) return JSON.parse(cbodys[0].value);

      var reQ = {};

      cbodys.forEach(el => {
        reQ[el.name] = JSON.path(el.value);
      });
      return JSON.parse(reQ);
    },
    setHeader(axiosData) {
      if (this.header.required) {
        var name = this.header.name;
        axiosData["headers"] = {};
        axiosData["headers"][name] = this.header.value;
      }
    },
    getHttp() {
      var cquerys = this.querys.filter(el => {
        return el.isChecked;
      });
      var axiosData = {
        method: "get",
        url: this.baseUrl + this.info.path,
        params: this.getParams(cquerys)
      };
      this.setHeader(axiosData);
      axios(axiosData).then(res => {
        this.response = res.data;
      });
    },
    postHttp() {
      var cbodys = this.bodys.filter(el => {
        return el.isChecked;
      });
      var axiosData = {
        method: "post",
        url: this.baseUrl + this.info.path,
        data: this.postParams(cbodys)
      };
      this.setHeader(axiosData);
      axios(axiosData).then(res => {
        this.response = res.data;
      });
    },
    handleJsonView(data) {
      console.log("34234");
    },
    fintTypeReturn(type) {
      switch (type) {
        case "integer":
          return 0;
        case "array":
          return [];
        case "object":
          return {};
        case "string":
          return "";
        default:
          return "";
      }
    },
    formatParameterModel(model) {
      var reModel = {};
      for (const key in model) {
        if (model.hasOwnProperty(key)) {
          const obj = model[key];
          reModel[key] = this.fintTypeReturn(model[key].type);
        }
      }
      return reModel;
    },
    getFormatQuerys() {
      let querys = this.info.data.parameters.filter(el => {
        return el.in == "query";
      });
      if (!querys || querys.length == 0) return;
      querys.forEach(el => {
        this.querys.push({
          description: el.description,
          name: el.name,
          isChecked: el.required,
          type: el.type,
          value: ""
        });
      });
    },
    getFormatBodys() {
      let bodys = this.info.data.parameters.filter(el => el.in == "body");

      if (!bodys || bodys.length == 0) return;
      bodys.forEach(el => {
        var model = this.getJsonModel(el.schema);
        this.bodys.push({
          description: el.description,
          name: el.name,
          isChecked: el.required,
          model: model,
          value: JSON.stringify(this.formatParameterModel(model))
        });
      });
    },
    ChooseMethod(tag) {
      switch (tag) {
        case "get":
          this.getFormatQuerys();
          break;
        case "post":
          this.getFormatBodys();
          break;
        default:
          break;
      }
    },
    getJsonModel(ref) {
      var model = this.findModelByRef(ref["$ref"]);
      return this.formatModel(model);
    },
    findModelByRef(ref) {
      let model = ref.split("/")[2];
      return this.$store.state.permission.models.find(el => {
        return el.name == model;
      });
    },
    //格式化Model
    formatModel(model) {
      var properties = model.properties;
      for (const key in properties) {
        if (properties.hasOwnProperty(key)) {
          const el = properties[key];
          if (el["type"] == "array") {
            if (el["items"]["$ref"]) {
              el["items"] = this.findModelByRef(el.items.$ref);
              if (el["items"].name == model.name) {
                el["items"] = {};
                continue;
              }
            }
            this.formatModel(el["items"]);
            el["type"] = "array";
          }
        }
      }
      return properties;
    },
    handleClick() {},
    filterTags(tag) {
      switch (tag) {
        case "post":
          return "success";
        case "get":
          return "info";
        default:
          break;
      }
    }
  },
  computed: {
    baseUrl() {
      return (
        this.$store.state.permission.schemes +
        "://" +
        this.$store.state.permission.host +
        "/"
      );
    },
    getMethod() {
      return this.info.method == "get" ? "PATH PARAMETERS" : "BODYS";
    },
    IsShow() {
      return this.info.method == "get";
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.debug {
  padding: 15px;
  .v-spn-1 {
    text-align: center;
    line-height: 32px;
  }
  .el-row {
    margin-bottom: 20px;
  }
  .path {
    margin-left: -0.5px;
  }
  .jv-container.jv-light {
    cursor: pointer;
  }
}
</style>
